package com.example.xinli.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.xinli.R;
import com.example.xinli.adapter.PostAdapter;
import com.example.xinli.model.Comment;
import com.example.xinli.model.Post;
import com.example.xinli.UserDbHelper;
import com.example.xinli.UserInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class CommunityFragment extends Fragment implements PostAdapter.OnPostActionListener {
    private RecyclerView recyclerPosts;
    private PostAdapter postAdapter;
    private List<Post> postList;
    private String currentUsername;
    private String currentNickname;
    private Bitmap selectedImageBitmap;
    private String selectedImagePath;

    // 用于图片选择的ActivityResultLauncher
    private ActivityResultLauncher<Intent> imagePickerLauncher;

    @SuppressLint("MissingInflatedId")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_community, container, false);

        // 初始化ActivityResultLauncher
        initImagePickerLauncher();

        // 添加发布按钮到Toolbar
        setupToolbar(view);

        // 初始化RecyclerView
        initViews(view);
        setupRecyclerView();

        // 加载示例数据
        loadSampleData();

        return view;
    }

    private void setupToolbar(View view) {
    // 获取已存在的发布按钮并设置点击事件
    ImageButton btnPublish = view.findViewById(R.id.btn_publish);
    if (btnPublish != null) {
        btnPublish.setOnClickListener(v -> showPublishDialog());
    }
}

private void initViews(View view) {
    recyclerPosts = view.findViewById(R.id.recycler_posts);

}


    private void setupRecyclerView() {
        postList = new ArrayList<>();
        postAdapter = new PostAdapter(postList, currentUsername);
        postAdapter.setOnPostActionListener(this);

        recyclerPosts.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerPosts.setAdapter(postAdapter);
    }

    private void loadSampleData() {
        // 添加一些示例数据
        Post post1 = new Post("1", "zhangsan", "张三", "今天天气真好，出去散步了！", "", System.currentTimeMillis());
        post1.getComments().add(new Comment("1", "lisi", "李四", "确实不错！", System.currentTimeMillis()));

        Post post2 = new Post("2", "lisi", "李四", "新学了一个Android开发技巧", "", System.currentTimeMillis() - 3600000);

        Post post3 = new Post("3", "wangwu", "王五", "周末去爬山，风景太美了！", "", System.currentTimeMillis() - 7200000);
        post3.getComments().add(new Comment("2", "zhangsan", "张三", "照片拍得真好！", System.currentTimeMillis()));
        post3.getComments().add(new Comment("3", "lisi", "李四", "下次一起去吧！", System.currentTimeMillis()));

        postList.add(post1);
        postList.add(post2);
        postList.add(post3);

        postAdapter.notifyDataSetChanged();
    }

    private void showPublishDialog() {
        Dialog dialog = new Dialog(getContext());
        dialog.setContentView(R.layout.dialog_publish_post);

        EditText etContent = dialog.findViewById(R.id.et_content);
        Button btnSelectImage = dialog.findViewById(R.id.btn_select_image);
        Button btnPublish = dialog.findViewById(R.id.btn_publish);
        ImageView ivSelectedImage = dialog.findViewById(R.id.iv_selected_image);

        btnSelectImage.setOnClickListener(v -> {
            // 打开图片选择器
            openImagePicker();
        });

        btnPublish.setOnClickListener(v -> {
            String content = etContent.getText().toString().trim();
            if (content.isEmpty()) {
                Toast.makeText(getContext(), "请输入动态内容", Toast.LENGTH_SHORT).show();
                return;
            }

            // 获取当前用户信息

            if (TextUtils.isEmpty(currentUsername)) {
                Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
                return;
            }

            UserInfo currentUser = UserDbHelper.getInstance(getContext()).login(currentUsername);
            if (currentUser == null) {
                Toast.makeText(getContext(), "用户信息获取失败", Toast.LENGTH_SHORT).show();
                return;
            }

            // 创建新动态
            Post newPost = new Post(
                    UUID.randomUUID().toString(),
                    currentUsername,
                    currentUser.getNickname(),
                    content,
                    selectedImagePath,
                    System.currentTimeMillis()
            );

            postList.add(0, newPost); // 添加到列表顶部
            postAdapter.notifyItemInserted(0);
            recyclerPosts.scrollToPosition(0);

            // 清空选择的图片
            selectedImageBitmap = null;
            selectedImagePath = null;

            dialog.dismiss();
            Toast.makeText(getContext(), "发布成功", Toast.LENGTH_SHORT).show();
        });

        dialog.show();
    }

    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        imagePickerLauncher.launch(intent);
    }

    private void initImagePickerLauncher() {
        imagePickerLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == getActivity().RESULT_OK && result.getData() != null) {
                        Uri imageUri = result.getData().getData();
                        try {
                            selectedImageBitmap = MediaStore.Images.Media.getBitmap(
                                    getActivity().getContentResolver(), imageUri);

                            // 保存图片到本地
                            selectedImagePath = saveImageToFile(selectedImageBitmap);

                            Toast.makeText(getContext(), "图片选择成功", Toast.LENGTH_SHORT).show();
                        } catch (IOException e) {
                            e.printStackTrace();
                            Toast.makeText(getContext(), "图片加载失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private String saveImageToFile(Bitmap bitmap) {
        if (getContext() == null) return null;

        try {
            // 创建图片文件路径
            File imagesDir = new File(getContext().getFilesDir(), "post_images");
            if (!imagesDir.exists()) {
                imagesDir.mkdirs();
            }

            String imagePath = new File(imagesDir, "post_" + System.currentTimeMillis() + ".png").getAbsolutePath();

            // 保存图片
            FileOutputStream out = new FileOutputStream(imagePath);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();

            return imagePath;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void onLikeClick(int position) {
        Post post = postList.get(position);
        if (post.isLiked()) {
            post.setLiked(false);
            post.setLikeCount(post.getLikeCount() - 1);
        } else {
            post.setLiked(true);
            post.setLikeCount(post.getLikeCount() + 1);
        }
        postAdapter.notifyItemChanged(position);
    }

    @Override
    public void onCommentClick(int position) {
        showAddCommentDialog(position);
    }

    @Override
    public void onShareClick(int position) {
        Post post = postList.get(position);
        String shareText = post.getNickname() + " 发布了动态：\n" + post.getContent();

        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, shareText);

        startActivity(Intent.createChooser(shareIntent, "分享动态"));
    }

    @Override
    public void onAddComment(int position, String commentContent) {
        Post post = postList.get(position);

        // 获取当前用户信息
        if (TextUtils.isEmpty(currentUsername)) {
            Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        UserInfo currentUser = UserDbHelper.getInstance(getContext()).login(currentUsername);
        if (currentUser == null) {
            Toast.makeText(getContext(), "用户信息获取失败", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建新评论
        Comment newComment = new Comment(
                UUID.randomUUID().toString(),
                currentUsername,
                currentUser.getNickname(),
                commentContent,
                System.currentTimeMillis()
        );

        post.getComments().add(newComment);
        postAdapter.notifyItemChanged(position);
        Toast.makeText(getContext(), "评论成功", Toast.LENGTH_SHORT).show();
    }

    private void showAddCommentDialog(int position) {
        Dialog dialog = new Dialog(getContext());
        dialog.setContentView(R.layout.dialog_add_comment);

        EditText etComment = dialog.findViewById(R.id.et_comment);
        Button btnSubmit = dialog.findViewById(R.id.btn_submit_comment);

        btnSubmit.setOnClickListener(v -> {
            String commentContent = etComment.getText().toString().trim();
            if (commentContent.isEmpty()) {
                Toast.makeText(getContext(), "请输入评论内容", Toast.LENGTH_SHORT).show();
                return;
            }

            onAddComment(position, commentContent);
            dialog.dismiss();
        });

        dialog.show();
    }

    // 提供给外部设置当前用户的方法
    public void setCurrentUser(String username) {
        this.currentUsername = username;

        // 获取用户昵称
        if (!TextUtils.isEmpty(username) && getContext() != null) {
            UserInfo user = UserDbHelper.getInstance(getContext()).login(username);
            if (user != null) {
                this.currentNickname = user.getNickname();
            }
        }
    }
}
